<?php

namespace System\Core;

if (!defined('BASEPATH')) die('Access Denied.');

/**
 * µMVC Framework (c) 2011.
 * 
 * PHP5 MVC Framework software for PHP 5.2.17 or later
 * 
 * @package         µMVC
 * @filename        system/core/registry.class.php
 * @copyright       Lanz (c) 2011.
 * 
 */

class RegistryException extends CommonException {}

/**
 * Registry class
 * Handle gobal classes accessible in controllers and models.
 * 
 * 
 * @package         µMVC
 * @subpackage      Core
 * @category        System
 */
class Registry extends BaseSingleton
{

    /**
     * The front controller object.
     * @var object
     */
    public $fc;
    /**
     * the uri object.
     * 
     * @var object
     */
    public $uri;
    
    /**
     * the input object deals with all inputs like params and $_POST messages. 
     * 
     * @var array
     */
    public $input;
    
    /**
     * The config object
     * @var object
     */
    public $config;
    
    /**
     * The registry object holds instances to the database, models and libraries.
     * 
     * @var object 
     */
    public $registry;

    /**
     * The loader object to load things like modules and libraries.
     * @var object
     */
    public $load;
    
    function __construct()
    {
        Log::instance()->write(Log::DEBUG, 'Registry Class Intitialized');
        $this->_loadBaseObjects();
    }

    private function _loadBaseObjects()
    {
        // Keep the names short and simple.
        $this->fc = FrontController::instance();
        $this->uri = URI::instance();
        $this->input = Input::instance();
        $this->config = Config::instance();
    }
    
    public function autoLoad()
    {
        // Initialize the database.
        $dbf = new \System\Database\DBFactory();
        $this->db = $dbf->connect();
        
        // Load models
        $models = Config::instance()->getItem('load_models');
        foreach($models as $value)
        {
            if (is_readable(BASEPATH.'models'.DS.$value.'.class.php'))
            {
                $model = '\\System\\Models\\'.$value;
                $this->{$value} = new $model();
            }
            else
            {
                throw new RegistryException("Can not auto load the $value model.");
            }
        }
        
        $helpers = Config::instance()->getItem('load_helpers');
        foreach($helpers as $value)
        {
            $helper = BASEPATH.'helpers'.DS.$value.'.helper.php';
            if (is_readable($helper))
            {
                include $helper;
            }
            else
            {
                throw new RegistryException("Can not auto load the $value helper.");
            }
        }
    }
    
}

?>
